package com.yy.controller.user;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yy.common.core.AjaxResult;
import com.yy.common.core.model.ComplainformVM;
import com.yy.common.core.model.RestaurantVM;
import com.yy.pojo.Complainform;
import com.yy.pojo.Restaurant;
import com.yy.pojo.User;
import com.yy.service.ComplainformService;
import com.yy.service.RestaurantService;
import com.yy.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/attachment")
public class ComplainController {

    @Autowired
    private ComplainformService complainformService;
    @Autowired
    private UserService userService;

    @Autowired
    private RestaurantService restaurantService;

    @GetMapping("/receiveRestaurant")
    public AjaxResult complaintRestaurant() {
        List<Restaurant> restaurantList = restaurantService.list(Wrappers.lambdaQuery(Restaurant.class).eq(Restaurant::getStatus,0));
        List<RestaurantVM> restaurantVMS = restaurantList.stream().map(r -> {
            RestaurantVM restaurantVM = new RestaurantVM();
            BeanUtils.copyProperties(r, restaurantVM);
            restaurantVM.setOpeningTime(DateUtil.format(r.getOpeningTime(), "HH:mm"));
            restaurantVM.setClosingTime(DateUtil.format(r.getClosingTime(), "HH:mm"));
            return restaurantVM;
        }).collect(Collectors.toList());
        return AjaxResult.success(restaurantVMS);
    }


    @PostMapping("/complaintForm")
    public AjaxResult complaintUser(@RequestBody ComplainformVM complainformVM) {

        Complainform complainform = new Complainform();

        complainform.setUserId(complainformVM.getUserId());
        complainform.setRestaurantId(complainformVM.getRestaurantId());
        complainform.setContent(complainform.getContent());
        complainform.setCreateTime(DateUtil.date());

        boolean save = complainformService.save(complainform);
        if(!save) {
            return AjaxResult.error();
        }

        User user = userService.getById(complainformVM.getUserId());
        complainformVM.setNickName(user.getNickName());
        complainformVM.setComplainformId(complainform.getComplainformId());
        complainformVM.setCreateTime(DateUtil.format(complainform.getCreateTime(),"yyyy年MM月dd日 HH:mm:ss"));

        return AjaxResult.success(complainformVM);
    }
}
